<template>
  <div class="conditionGroup">
    <el-row class="first">
      <div class="hverCenter">
        <label>所属电厂</label>
        <CdnSelect
          :options="plantList"
          v-model="param.plantCode"
          :model="model"
        />
      </div>
      <div class="hverCenter">
        <label>类型</label>
        <CdnSelect
          :options="options"
          v-model="param.yearType"
        />
      </div>
      <div class="hverCenter">
        <label>机组容量（千瓦）</label>
        <CdnInput v-model="param.capacity" />
      </div>
      <div class="hverCenter">
        <label>投运时间</label>
        <CdnPicker
          type="date"
          v-model="param.start"
        />
        <span>&nbsp;-&nbsp;</span>
        <CdnPicker
          type="date"
          v-model="param.end"
        />
      </div>
      <div class="hverCenter">
        <label>年份</label>
        <CdnPicker
          type="year"
          v-model="param.periods"
        />
      </div>
      <div class="hverCenter">
        <CdnButton
          class="query"
          text="查询"
          @click="query"
        />
        <CdnButton
          class="reset"
          text="重置"
          @click="reset"
        />
      </div>

    </el-row>
    <el-row class="second">
      <el-col
        :span="12"
        :push="12"
        class="right"
      >
        <CdnButton
          class="query"
          text="导出"
          @click="exportTo"
        />
        <CdnButton
          class="query"
          text="新增"
          @click="add"
        />
        <CdnButton
          class="query"
          text="修改"
          @click="update"
        />
        <CdnButton
          class="query"
          text="有效"
          @click.prevent="toggle('1')"
        />
        <CdnButton
          class="query"
          text="无效"
          @click.prevent="toggle('0')"
        />
        <CdnButton
          class="query"
          text="删除"
          @click.prevent="remove"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import CdnButton from '@/views/stagePower/CdnButton';
import CdnInput from '@/views/stagePower/CdnInput';
import CdnSelect from '@/views/stagePower/CdnSelect';
import CdnPicker from '@/views/stagePower/CdnPicker';
import { ref, inject, reactive } from 'vue';
import { showMsg, resetObj } from '@/utils/frequency';
import { deleteUnitList, toggleValid } from '@/services/stagePower';

const visibleDia = inject('visibleDia');
const operFlag = inject('operFlag');
const selectedRow = inject('selectedRow');

const prop = defineProps({
  plantList:{ // 方案列表
    type: Array,
    default: []
  }, model: { // 方案模型
    type: Object,
    default: {}
  }, selectedList: { // 表格中选中的对象集合
    type: Array,
    default: []
  }
});
const emit = defineEmits(['queryUnitList', 'resetSelectedRow', 'exportUnitList']);

// 查询条件
const param = inject('param');

const reset = () => {
  resetObj(param);
  query();
}


/**
 * 下载excel文件模板，需要查表
 * @param { String } url excel 请求路径
 * @param { Object } param 路径参数
 * @param { String } fileName 文件名称
 */
 function getExcelTemplate (url, param, fileName = '模板.xlsx') {
  // 前端使用XHR发送POST请求
  let xhr = new XMLHttpRequest();
  xhr.open('POST', url);
  // 设置响应格式
  xhr.responseType = 'blob';
  // 设置请求头
  xhr.setRequestHeader('Content-Type', 'application/json');
  // 将数据序列化为JSON字符串
  let data = JSON.stringify(param);
  xhr.send(data); // 发送请求和数据

  // 请求成功
  xhr.onload = function () {
    if (xhr.status === 200) {

      var downloadLink = document.createElement('a');
      downloadLink.href = window.URL.createObjectURL(xhr.response);
      downloadLink.download = fileName;
      downloadLink.style.display = 'none';
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    }
  };

  // 请求失败
  xhr.onerror = function () {
    showWarnDialog(`请求失败`);
  };
}

const exportTo = () => {
  
  emit('exportUnitList');
}

// 新增机组
const add = () => {
  emit('resetSelectedRow');
  operFlag.value = 0;
  visibleDia.value = true;
}

// 更新机组
const update = () => {
  if (selectedRow.length != 1) return showMsg('请选择一条数据');
  operFlag.value = 1;
  visibleDia.value = true;
}

// 查询机组
const query = () => {
  if (param.start != null || param.end != null) {
    if (param.end == null) return showMsg('请选择结束日期');
    if (param.start == null) return showMsg('请选择开始日期');
  }
  emit('queryUnitList');
}

// 删除机组
const remove = async () => {
  const list = getSelectedListKeys();
  if (list.length == 0) return showMsg('请选择数据');
  const { respStatus, respMessage, respData } = await deleteUnitList({ list });
  if(!respStatus) return showMsg(respMessage);
  emit('queryUnitList', param);
}

// 修改机组有效无效
const toggle = async (valid) => {
  const list = getSelectedListKeys();
  if (list.length == 0) return showMsg('请选择数据');
  for(let i = 0; i < list.length; i++) list[i].valid = valid; // 添加有效信息
  
  const { respStatus, respMessage, respData } = await toggleValid({list});
  if(!respStatus) return showMsg(respMessage);
  emit('queryUnitList', param);
}

// 获取选中列表的键对象，其中 PLANT_CODE, YEAR_TYPE, PERIODS 三个属性构成一个主键
const getSelectedListKeys = () => {
  const selectedList = prop.selectedList;
  return selectedList.map(item =>  {
    return {
      'PLANT_CODE': item.PLANT_CODE,
      'YEAR_TYPE': item.YEAR_TYPE,
      'PERIODS': item.PERIODS,
    }
  });
}


const options = ref([
  {
    'key': '1',
    'value': '丰水年'
  },
  {
    'key': '2',
    'value': '平水年'
  },
  {
    'key': '3',
    'value': '枯水年'
  },
])

</script>

<style lang="scss">
.conditionGroup {
  width: 100%;
  * {
    box-sizing: border-box;
  }
  .first,
  .second {
    padding: 10px;
  }
  .first > div {
    padding: 0px 5px;
    label {
      padding-right: 5px;
    }
  }
  .hverCenter {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .query,
  .reset {
    margin: 0 4px;
  }
  .right {
    display: flex;
    justify-content: flex-end;
  }
}
</style>